﻿using System;
using System.Collections.Generic;
using System.Linq;
using Infragistics.Win.UltraWinDataSource;
using Infragistics.Win.UltraWinGrid;
using LS9.Common;
using LS9.DataAccess;
using LS9.Win;
using LS9.Win.Controls;

namespace LS9.LimS9.Controls
{
	public partial class PrintLibraryPlates : ControlBase, IPrintLabelsPlugin
	{
		private Lims9DataSet.LibraryRow _libRow;
		private IPrintLabelsHost _host;

		ControlBase IPrintLabelsPlugin.Control
		{
			get { return this; }
		}

		public PrintLibraryPlates( Lims9DataSet.LibraryRow row )
		{
			if( !Util.IsValid( row ) )
			{
				throw new Exception9( Enums.Severity.Error, "PrintLabels: The Library is invalid" );
			}
			_libRow = row;

			InitializeComponent();
		}

		/// <summary>
		/// Constructor for creating Library Plates
		/// </summary>
		/// <param name="services"></param>
		void IPrintLabelsPlugin.InitializePlugin( IPrintLabelsHost host )
		{
			_host = host;
			host.SetText( "Print Labels" );
			host.SetTitle( "Print Labels for Library Plates" );
			string libText =
				"The following {0} {1} are associated with library {2}.\n\n" +
				"Select the plates for which you want to (re)print a barcode label.";
			int n = Data.Container.Rows().Count( r => r.LibraryId == _libRow.LibraryId );
			lblLibPlates.Text = String.Format( libText, n, Pluralizer.ToPlural( "plate", n ), _libRow.Moniker );

			var lcs = Data.Container.Rows().Where( lc => lc.LibraryId == _libRow.LibraryId );
			var cs = DataModel.Container.ListContainers( lcs.Select( r => r.ContainerId ) );
			foreach( var lc in lcs )
			{
				var c = cs.Single( o => o.ContainerId == lc.ContainerId );
				labelsData.Rows.Add( new object[] { c.LS9Id, lc.LibraryIndex + 1, false, String.Format( "{0} P{1}", lc.LibraryRow.Moniker, lc.LibraryIndex + 1 ) } );
			}

			_host.EnableOk( true );
		}

		/// <summary>
		/// Create library plate labels
		/// </summary>
		void IPrintLabelsPlugin.CreateLabels( List<BarcodeLabel> labels )
		{
			var rows = labelsData.Rows.OfType<UltraDataRow>().Where( dr => (bool)dr["Print"] ).ToList();
			foreach( var dr in rows )
			{
				string bc = (string)dr["Barcode"];
				string title = String.Format( "Plate {0} - P{1:00}", _libRow.Moniker, (int)dr["Index"] );
				string desc = String.Format( "{0} Library [{1}]", Model.GetChoice( _libRow.TypeEnum ), _libRow.LS9Id );
				string ts = String.Format( "{0} on {1}", Services.UserName, Util.Date9 );
				labels.Add( new BarcodeLabel( Enums.Printing.Stock.Plate, bc, title, desc ) );
			}
		}

		private void PlateGrid_InitializeLayout( object sender, InitializeLayoutEventArgs e )
		{
			plateGrid.DisplayLayout.Bands[0].Columns["Barcode"].Hidden = true;
			plateGrid.DisplayLayout.Bands[0].Columns["Index"].Hidden = true;
		}
	}
}
